<template>
  <div class="app-container">
    <SearchFilter size="medium" :maxShow="3" @search="handleQuery" @reset="resetQuery">
      <el-form :model="queryParams" label-position="right" label-width="70px" ref="queryForm">
        <el-row  :gutter="20">
          <el-col :span="7">
            <el-form-item label="设备" prop="equipmentId">
              <el-input
                v-model="queryParams.equipmentId"
                placeholder="请输入设备"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="项目" prop="projectId">
              <el-input
                v-model="queryParams.projectId"
                placeholder="请输入项目"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="片区" prop="areaId">
              <el-input
                v-model="queryParams.areaId"
                placeholder="请输入片区"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="截止时间" prop="endDate">
              <el-date-picker clearable
                v-model="queryParams.endDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择截止时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="项目经理" prop="projectManager">
              <el-input
                v-model="queryParams.projectManager"
                placeholder="请输入项目经理"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="维修人员" prop="repairPerson">
              <el-input
                v-model="queryParams.repairPerson"
                placeholder="请输入维修人员"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </SearchFilter>

    <div class="content-container">
      <el-row :gutter="10" class="mb8" type="flex" justify="space-between">
        <el-col :span="1.5">
          <p class="header-title">零散报修列表</p>
        </el-col>
        <div>
          <el-col :span="1.5" v-if="ids.length">
            <el-button
              size="small"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['work:report:remove']"
            >批量删除</el-button>
          </el-col>
          <el-col :span="1.5" v-if="ids.length">
            <el-button
              size="small"
              :disabled="multiple"
              icon="el-icon-download"
              @click="handleExport"
              v-hasPermi="['work:report:export']"
            >批量导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="small"
              @click="handleAdd"
              v-hasPermi="['work:report:add']"
            >新增报修</el-button>
          </el-col>
        </div>
      </el-row>

      <el-table v-loading="loading" :data="reportList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="维修项目" align="center" prop="project" />
        <el-table-column label="定位" align="center" prop="position" />
        <el-table-column label="报修联系人" align="center" width="120" prop="repairUser" />
        <el-table-column label="报修联系方式" align="center" width="120" prop="repairPhone" />
        <el-table-column label="维修人员" align="center" width="120" prop="repairPerson" />
        <el-table-column label="维修人员电话" align="center" width="120" prop="repairPersonPhone" />
        <el-table-column label="报修内容" align="center" width="120" prop="remark" />
        <el-table-column label="报修状态" align="center" width="120" prop="status">
          <template slot-scope="scope">
            <div style="display: flex; align-items: center; justify-content: center;">
              <span class="wait-round" v-if="scope.row.status === 0"></span>
              <span class="already-round" v-if="scope.row.status === 1"></span>
              <span>{{ changeStatus(scope.row.status) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="报修标签" align="center" width="120" prop="reStatus">
          <template slot-scope="scope">
            <div style="display: flex; align-items: center; justify-content: center;">
              <span class="wait-round" v-if="['申请延期', '拒绝延期', '同意延期'].includes(changeReStatus(scope.row.statusText))"></span>
              <!-- <span class="time-out-round " v-if="scope.row.status1 === 1"></span> -->
              <span class="delay-round " v-if="['申请退单', '拒绝退单', '同意退单'].includes(changeReStatus(scope.row.statusText))"></span>
              <span>{{ changeReStatus(scope.row.statusText) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="220" fixed="right" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              class="text-text table-btn"
              v-hasPermi="['work:report:query']"
              @click="getRouterInfo(scope.row)"
            >查看</el-button>
            <el-button
              size="mini"
              type="text"
              class="text-danger table-btn"
              @click="handleDelete(scope.row)"
              v-hasPermi="['work:report:remove']"
            >删除</el-button>
            <el-button
              size="mini"
              type="text"
              v-if="changeReStatus(scope.row.statusText) === '申请退单'"
              @click="getRouterInfo(scope.row)"
            >退单查看</el-button>
            <el-button
              size="mini"
              type="text"
              class="text-warning"
              v-if="changeReStatus(scope.row.statusText) === '申请延期'"
              @click="getRouterInfo(scope.row)"
            >延期查看</el-button>
            <el-button
              size="mini"
              type="text"
              v-if="changeReStatus(scope.row.statusText) === '申请转单'"
              @click="getRouterInfo(scope.row)"
            >转单查看</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>

    <!-- 添加或修改报修工单信息对话框 -->
    <!-- 报修设备、报修位置、报修联系人、报修联系人电话、维修员、维修员电话、截止时间、报修图片、报修视频、报修备注 -->
    <el-dialog :title="title" custom-class="dialog" :visible.sync="open" append-to-body :close-on-click-modal="false" width="740px">
      <el-form ref="form" :model="form" :rules="rules" label-position="top" label-width="80px">
        <el-row type="flex" justify="space-between">
          <el-col :span="11">
            <el-form-item label="维修项目" prop="project">
              <el-input v-model="form.project" placeholder="设备名称" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="定位" prop="position">
              <el-input v-model="form.position" placeholder="请输入片区id" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="space-between">
          <el-col :span="11">
            <el-form-item label="报修联系人" prop="repairUser">
              <el-input v-model="form.repairUser" placeholder="请输入保修电话" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="报修联系方式" prop="repairPhone">
              <el-input v-model="form.repairPhone" placeholder="请输入保修电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="space-between">
          <el-col :span="11">
            <el-form-item label="维修人员" prop="repairPerson">
              <el-select v-model="form.repairPerson" multiple  placeholder="请输入维修人员" @change="repairChange">
                <el-option
                  v-for="item in repairOptions"
                  :key="item.nickName"
                  :label="item.nickName"
                  :value="item.nickName">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="维修人员电话" prop="repairPersonPhone">
              <el-input v-model="form.repairPersonPhone" placeholder="请输入维修人员电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="space-between">
          <el-col :span="11">
            <el-form-item label="截止时间" prop="endDate">
              <el-date-picker clearable v-model="form.endDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择截止时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="space-between">
            <el-col :span="24">
              <el-form-item label="报修内容" prop="repairRemark">
                <el-input v-model="form.repairRemark" type="textarea" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
          </el-row>
        <el-row type="flex" justify="space-between">
          <el-col :span="24">
            <el-form-item label="图片" prop="repairImg">
              <image-upload v-model="form.repairImg"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="space-between">
          <el-col :span="24">
            <el-form-item label="视频" prop="repairVideo">
              <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :data="{ file_type: 'video' }"
                v-bind:on-progress="uploadVideoProcess"
                v-bind:on-success="handleVideoSuccess"
                v-bind:before-upload="beforeUploadVideo"
                v-bind:show-file-list="false"
                :headers="{
                    Authorization: 'Bearer ' + $store.state.user.token,
                }">
                  <video
                    v-if="videoForm.showVideoPath != '' && !videoFlag"
                    v-bind:src="videoForm.showVideoPath"
                    class="avatar video-avatar"
                    controls="controls">
                    您的浏览器不支持视频播放
                  </video>
                  <div class="file-upload" v-else-if="videoForm.showVideoPath == '' && !videoFlag">
                    <i class="el-icon-plus avatar-uploader-icon"></i>
                  </div>
                  <el-progress
                    v-if="videoFlag == true"
                    type="circle"
                    v-bind:percentage="videoUploadPercent"
                    style="margin-top: 7px">
                  </el-progress>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listReport, getReport, delReport, addReport, updateReport } from "@/api/work/report";
import { listArea } from '@/api/resource/area'
import { listProject } from '@/api/resource/project'
import { getUserList } from '@/api/menu';
import { listEquipment, getEquipment } from "@/api/resource/equipment";
import SearchFilter from '@/components/SearchFile'

export default {
  name: "Repair",
  components: { SearchFilter },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报修工单信息表格数据
      reportList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        equipmentId: null,
        projectId: null,
        areaId: null,
        position: null,
        endDate: null,
        owner: null,
        ownerUnit: null,
        unitArea: null,
        ownerPhone: null,
        contractDate: null,
        contractEndDate: null,
        projectManager: null,
        projectManagerPhone: null,
        repairPerson: null,
        repairPersonPhone: null,
        repairVideo: null,
        repairImg: null,
        repairUser: null,
        repairPhone: null,
        repairRemark: null,
        status: null,
        reStatus: null,
        version: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        equipmentName: [
          { required: true, message: '设备名称不能为空', trigger: "blur" }
        ],
        endDate: [
          { required: true, message: '截止时间不能为空', trigger: "blur" }
        ],
        repairPerson: [
          { required: true, message: '维修人员不能为空', trigger: "blur" }
        ],
        repairUser: [
          { required: true, message: '报修联系人不能为空', trigger: "blur" }
        ],
        repairPhone: [
          { required: true, message: '报修人联系方式不能为空', trigger: "blur" },
          { pattern: /(1[34578]\d{9})$/, message: "请填写正确的手机号码", trigger: "change" }
        ]
      },
      projectOptions: [],
      areaOptions: [],
      deviceList: [],
      managerList: [],
      repairOptions: [],
      videoFlag: false,
      //是否显示进度条
      videoUploadPercent: "",
      //进度条的进度，
      isShowUploadVideo: false,
      //显示上传按钮
      videoForm: {
          showVideoPath: "", //回显的变量
      },
      uploadUrl: process.env.VUE_APP_BASE_API + '/file/upload',
      baseUrl: process.env.VUE_APP_BASE_API,
    };
  },
  created() {
    this.getProjectList()
    this.getAreaList()
    this.getUserListHandle()
    this.getDeviceList()
    this.getList();
  },
  methods: {
    uploadVideoProcess(event, file, fileList) {
      //注意在data中添加对应的变量名
      this.videoFlag = true;
      this.videoUploadPercent = file.percentage.toFixed(0) * 1;
    },
    //上传前回调
    beforeUploadVideo(file) {
      var fileSize = file.size / 1024 / 1024 < 50; //控制大小  修改50的值即可
      if (
          [
              "video/mp4",
              "video/ogg",
              "video/flv",
              "video/avi",
              "video/wmv",
              "video/rmvb",
              "video/mov",
          ].indexOf(file.type) == -1 //控制格式
      ) {
          this.$message.error("请上传正确的视频格式");
          return false;
      }
      if (!fileSize) {
          this.$message.error("视频大小不能超过50MB");
          return false;
      }
      this.isShowUploadVideo = false;
    },
    //上传成功回调
    handleVideoSuccess(res, file) {
      console.log(res)
      // let decrypt = new JSEncrypt();
      // decrypt.setPrivateKey(config.cert.privateKey);
      // var decryptMsg = decrypt.decryptLong(res, "utf-8");
      // res = JSON.parse(decryptMsg);
      // this.isShowUploadVideo = true;
      this.videoFlag = false;
      this.videoUploadPercent = 0;
      console.log("成功", res);
      //后台上传数据
      if (res.code == 200) {
        this.videoForm.showVideoPath = this.baseUrl + '/file/download?name=' + res.data; //上传成功后端返回视频地址 回显
        this.form.repairVideo = '/file/download?name=' + res.data;
      } else {
        this.$message.error("上传失败！");
      }
    },
    /** 查询项目 */
    async getProjectList() {
      const res = await listProject({ deptId: this.$store.state.user.user.deptId, pageNum: -1 })
      this.projectOptions = res.rows
    },
    /** 查询片区 */
    async getAreaList() {
      const res = await listArea({ deptId: this.$store.state.user.user.deptId, pageNum: -1 })
      this.areaOptions = res.rows
    },
    async getUserListHandle() {
      const deptCode = this.$store.state.user.user.dept.deptCode
      const roleKey = deptCode.substring(deptCode.length - 4)
      const managerRes = await getUserList({ roleKey: roleKey + '-manager' })
      if (managerRes.data.length) {
        this.managerList = managerRes.data.map(item => {
          return { ...item, userId: item.userId + '' }
        })
      }
      const repairRes = await getUserList({ roleKey: roleKey + '-repair' })
      if (repairRes.data.length) {
        this.repairOptions = repairRes.data.map(item => {
          return { ...item, userId: item.userId + '' }
        })
      }
    },
    
    managerChange(e) {
      let obj = this.managerList.find(item => item.nickName === e)
      this.form.projectManagerPhone = obj.phonenumber
    },
    repairChange(e) {
      this.form.repairPersonPhone = ''
      let phoneStr = []
      e.forEach(items => {
        let obj = this.repairOptions.find(item => item.nickName === items)
        phoneStr.push(obj.phonenumber)
      })
      this.form.repairPersonPhone = phoneStr.toString()
    },
    /** 设备列表 */
    async getDeviceList() {
      const res = await listEquipment({ deptId: this.$store.state.user.user.deptId, pageNum: -1 })
      if (res.rows.length) {
        this.deviceList = res.rows.map(item => {
          return {name: item.equipmentName, value: item.id}
        })
      } else {
        this.deviceList = []
      }
    },
    /** 查询设备详情 */
    // async selectChange(val) {
    //   const res = await getEquipment(val)
    //   console.log(res)
    //   this.form = {
    //     equipmentId: res.data.id,
    //     equipmentType: res.data.equipmentType + '',
    //     equipmentCode: res.data.equipmentCode,
    //     equipmentFirm: res.data.equipmentFirm,
    //     projectId: res.data.projectId,
    //     areaId: res.data.areaId,
    //     position: res.data.position,
    //     endDate: res.data.endDate,
    //     ownerUnit: res.data.ownerUnit,
    //     unitArea: res.data.unitArea,
    //     owner: res.data.owner,
    //     ownerPhone: res.data.ownerPhone,
    //     contractDate: res.data.contractDate,
    //     contractEndDate: res.data.contractEndDate,
    //     projectManager: res.data.projectManager,
    //     projectManagerPhone: res.data.projectManagerPhone,
    //     // repairPerson: res.data.repairPerson,
    //     // repairPersonPhone: res.data.repairPersonPhone,
    //     remark: res.data.remark,
    //     repairImg: res.data.repairImg,
    //     repairVideo: res.data.repairVideo
    //   }
    // },
    /** 查询报修工单信息列表 */
    getList() {
      this.loading = true;
      listReport({...this.queryParams, deptId: this.$store.state.user.user.deptId, orderByColumn: 'id', isAsc: 'desc' }).then(response => {
        this.reportList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    changeStatus(val) {
      let str = ''
      switch (val) {
        case 0:
          str = '待处理'; break;
        case 1:
          str = '已处理'; break;
        default: break;
      }
      return str
    },
    changeReStatus(val) {
      if (!(val && val.length)) return
      let arr = JSON.parse(val)
      let obj = arr[arr.length - 1]
      if (obj.statusType === 2) {
        if (obj.status === 0) {
          return '申请退单'
        }
        if (obj.status === 1) {
          return '拒绝退单'
        }
        if (obj.status === 2) {
          return '同意退单'
        }
      }
      if (obj.statusType === 3) {
        if (obj.status === 0) {
          return '申请延期'
        }
        if (obj.status === 1) {
          return '拒绝延期'
        }
        if (obj.status === 2) {
          return '同意延期'
        }
      }
      if (obj.statusType === 4) {
        if (obj.status === 0) {
          return '申请转单'
        }
        if (obj.status === 1) {
          return '拒绝转单'
        }
        if (obj.status === 2) {
          return '同意转单'
        }
      }
    },
    /** 跳转详情 */
    getRouterInfo({ id }) {
      this.$router.push("/work/reportQuery/" + id);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        equipmentId: null,
        projectId: null,
        areaId: null,
        position: null,
        endDate: null,
        owner: null,
        ownerUnit: null,
        unitArea: null,
        ownerPhone: null,
        contractDate: null,
        contractEndDate: null,
        projectManager: null,
        projectManagerPhone: null,
        repairPerson: [],
        repairPersonPhone: null,
        remark: null,
        repairVideo: null,
        repairImg: null,
        repairPhone: null,
        repairRemark: null,
        status: null,
        reStatus: null,
        version: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加报修工单信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getReport(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改报修工单信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let str = ''
          console.log(this.form)
          if (this.form.repairPerson.length) {
            str = this.form.repairPerson.toString()
          }
          if (this.form.id != null) {
            updateReport({...this.form, repairPerson: str, deptId: this.$store.state.user.user.deptId }).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addReport({ ...this.form, repairPerson: str, deptId: this.$store.state.user.user.deptId }).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除报修工单信息编号为"' + ids + '"的数据项？').then(function () {
        return delReport(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('work/repair/export', {
        ...this.queryParams
      }, `repair_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style lang="scss" scoped>
.file-upload {
  width: 104px;
  height: 104px;
  background-color: #fbfdff;
  border: 1px dashed #c0ccda;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  .el-icon-plus {
    font-size: 28px;
    color: #8c939d;
  }
}
.video-avatar {
  width: 104px;
  height: 104px;
}
</style>